/**
 * Flash message jQuery UI widget.
 * @author Christoffer Niska <ChristofferNiska@gmail.com>
 * @copyright  Copyright &copy; Christoffer Niska 2011-
 * @license http://www.opensource.org/licenses/bsd-license.php New BSD License
 */

(function($) {

	$.widget('ui.flashmessage', {
		/**
		 * The default options for this widget.
		 * @type Object
		 */
		options: {
			keys: ['success','error','notice'],
			template: '<div class="{key}">{message}</div>',
			displayTime: 3000,
			fadeTime: 600
		},
		_init: function() {
			this.flash();
		},
		/**
		 * Sets a flash message for the user.
		 * @param {String} key the flash message key.
		 * @param {String} message the message to display.
		 * @throws Error if the key is invalid.
		 */
		setFlash: function(key, message) {
			// Make sure that the given key is valid.
			if (this.options.keys.indexOf(key) !== -1) {
				var html = this.options.template;
				html = html.replace('{key}', key);
				html = html.replace('{message}', message);
				this.element.html(html);
				this.element.show();
				this.flash();
			} else {
				throw new Error('Setting flash message failed. Key `' + key + '` is invalid!');
			}
		},
		/**
		 * Flashes the flash message.
		 */
		flash: function() {
			this.element.animate({ opacity: 1.0	}, this.options.displayTime);

			this.element.fadeOut(this.options.fadeTime, function() {
				$(this).html(''); // we need to make sure that no old messages are left hanging around
			});
		}
	});

})(jQuery);